/*
 * Copyright (c) 2016 zhangcm. All Rights Reserved.
 */
package com.deram.ctin.tool.zuul.filter;

import com.deram.ctin.common.utils.CookieUtils;
import com.deram.ctin.common.utils.TokenUtils;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zhangcm
 * @version 1.0, 2017/9/17
 */
@Component
public class TokenFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 10;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext context = RequestContext.getCurrentContext();
        String token = TokenUtils.getFromCookie(context.getRequest());
        return StringUtils.isEmpty(token);
    }

    @Override
    public Object run() {
        RequestContext context = RequestContext.getCurrentContext();
        String token = TokenUtils.create();
        CookieUtils.setCookie(context.getResponse(), TokenUtils.TOKEN_NAME, token);
        context.addZuulRequestHeader(TokenUtils.TOKEN_NAME, token);
        return null;
    }
}
